﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Expo.Training.Entity;
using PPTech.ESP.DataProvider;
using Expo.Training.DataAccess.Exam;
using System.Text.RegularExpressions;
using System.IO;
using Expo.Training.BRule;
using Expo.Training.BRule.Audit;
using System.Data;
using Expo.Training.BRule.Member;
using System.Net;
using System.Web.Script.Serialization;
using System.Text;
using System.Configuration;
using Expo.Training.DataAccess.Vip;

public partial class User_EditUser99XB : PageBase
{
    public Guid UserID = Guid.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            this.UserID = new Guid(Request.QueryString["id"].Trim());
        }
        catch { return; }

        if (!IsPostBack)
        {
            BindCityList(0, 0);
            BindUserBasic();
        }
    }

    private void BindCityList(int areaKey,int type)
    {
        this.ddl_WordAddress_Province.DataSource = BindCityDate(1, 0);
        this.ddl_WordAddress_Province.DataTextField = "AreaName";
        this.ddl_WordAddress_Province.DataValueField = "AreaId";
        this.ddl_WordAddress_Province.DataBind();
        this.ddl_WordAddress_Province.Items.Insert(0, new ListItem("  ---  请选择  ---  ", "0"));

        this.ddl_HomeAddress_Province.DataSource = BindCityDate(1, 0);
        this.ddl_HomeAddress_Province.DataTextField = "AreaName";
        this.ddl_HomeAddress_Province.DataValueField = "AreaId";
        this.ddl_HomeAddress_Province.DataBind();
        this.ddl_HomeAddress_Province.Items.Insert(0, new ListItem("  ---  请选择  ---  ", "0"));

        if (type == 1)
        {
            this.ddl_WordAddress_City.DataSource = BindCityDate(2, areaKey);
            this.ddl_WordAddress_City.DataTextField = "AreaName";
            this.ddl_WordAddress_City.DataValueField = "AreaId";
            this.ddl_WordAddress_City.DataBind();
        }
        else if (type == 2)
        {
            this.ddl_WordAddress_Area.DataSource = BindCityDate(3, areaKey);
            this.ddl_WordAddress_Area.DataTextField = "AreaName";
            this.ddl_WordAddress_Area.DataValueField = "AreaId";
            this.ddl_WordAddress_Area.DataBind();
        }
        else if (type == 3)
        {
            this.ddl_HomeAddress_City.DataSource = BindCityDate(2, areaKey);
            this.ddl_HomeAddress_City.DataTextField = "AreaName";
            this.ddl_HomeAddress_City.DataValueField = "AreaId";
            this.ddl_HomeAddress_City.DataBind();
        }
        else if (type == 4)
        {
            this.ddl_HomeAddress_Area.DataSource = BindCityDate(3, areaKey);
            this.ddl_HomeAddress_Area.DataTextField = "AreaName";
            this.ddl_HomeAddress_Area.DataValueField = "AreaId";
            this.ddl_HomeAddress_Area.DataBind();
        }
    }

    private DataTable BindCityDate(int nodeType, int areaKey)
    {
        DataTable objData = new DataTable();
        City_Info objCity = new City_Info();
        objCity.NodeType = nodeType;
        objCity.AreaKey = areaKey;
        objCity.OrderBy = "Px";
        objData = objCity.QueryDataTable();
        objCity.Dispose();
        return objData;
    }

    public void BindUserBasic()
    {
        Member_Info objMember = new Member_Info();
        objMember.MemberID = this.UserID;
        objMember.CustomerID = this.Member.CustomerID;
        if (!objMember.Exist())
            return;
        BindCityList(objMember.WorkAddress_Province, 1);
        BindCityList(objMember.WorkAddress_City, 2);
        BindCityList(objMember.HomeAddress_Province, 3);
        BindCityList(objMember.HomeAddress_City, 4);
        if (objMember.HeaderUrl.Length == 0)
            this.img_Header.ImageUrl = ResolveClientUrl("~/Data/Header/defaultheader.jpg");
        else
            this.img_Header.ImageUrl = ResolveClientUrl("~/Data/Header/" + objMember.HeaderUrl);
        this.txt_UserAccount.Text = objMember.UserAccount;
        if (objMember.UserAccount.ToLower() == "admin")
        {
            txt_UserAccount.Enabled = false;
        }
        this.txt_RealName.Text = objMember.RealName;
        this.txt_NickName.Text = objMember.NickName;
        this.ddl_Sex.SelectedValue = objMember.Sex.ToString();
        this.ddl_CardType.SelectedValue = objMember.CardType.ToString();
        this.txt_Duty.Text = objMember.Duty;
        this.txt_IDCard.Text = objMember.IDCard;
        this.txt_Email.Text = objMember.Email;
        this.txt_CellPhone.Text = objMember.CellPhone;
        this.ddl_WordAddress_Province.SelectedValue = objMember.WorkAddress_Province.ToString();
        this.ddl_HomeAddress_Province.SelectedValue = objMember.HomeAddress_Province.ToString();
        this.ddl_HomeAddress_Area.SelectedValue = objMember.HomeAddress_Area.ToString();
        this.hd_HomeAddress_Area.Value = objMember.HomeAddress_Area.ToString();
        this.hd_HomeAddress_City.Value = objMember.HomeAddress_City.ToString();
        this.ddl_HomeAddress_City.SelectedValue = objMember.HomeAddress_City.ToString();
        
        this.ddl_WordAddress_Area.SelectedValue = objMember.WorkAddress_Area.ToString();
        this.hd_WordAddress_Area.Value = objMember.WorkAddress_Area.ToString();
        this.ddl_WordAddress_City.SelectedValue = objMember.WorkAddress_City.ToString();
        this.hd_WordAddress_City.Value = objMember.WorkAddress_City.ToString();
        //this.txt_HomeAddress.Text = objMember.HomeAddress;

        Exam_Question_AttributeMapping objQMapping = new Exam_Question_AttributeMapping();
        objQMapping.QuestionID = this.UserID;
        DataBox details = objQMapping.Query();
        if (details != null && details.Count > 0)
        {
            List<QuestionAttributeDetailEntity> bindDetails = new List<QuestionAttributeDetailEntity>();
            foreach (Exam_Question_AttributeMapping map in details.EntityInstanceCollection)
            {
                QuestionAttributeDetailEntity objQDetail = new QuestionAttributeDetailEntity();
                objQDetail.AttributeID = map.AttributeID;
                objQDetail.DetailID = map.DetailID;

                bindDetails.Add(objQDetail);
            }

            ta_Attributes.SelectedValue = bindDetails;
        }

        //2013.3.8 绑定学习卡
        MemberCard_Info mci = new MemberCard_Info();
        mci.MemberID = objMember.MemberID;
        if (mci.Exist())
        {
            txtCardID.Text = mci.CardID;
        }

        //2013.3.8 增加教师，志愿者相关信息
        //ddlMemberType.SelectedValue = objMember.MemberType.ToString();
        //txtSpecialty.Text = objMember.Specialty;
        if (objMember.Volunteer == 1)
        {
            chkIsVolunteer.Checked = true;
        }
        else
        {
            chkIsVolunteer.Checked = false;
        }
        //txtMemo.Text = objMember.Memo;

        if (objMember.Stutas == 0)
            this.rbt_Y.Checked = true;
        else
            this.rbt_N.Checked = true;


        //绑定VIP等级
        VipEntity _vip = new VipEntity();
        string _vipTitle;
        if (!string.IsNullOrEmpty(mci.CardID))
        {
            _vip = VipModule.GetVipByMemberID(this.UserID);
            _vipTitle = _vip.CategoryName;

            if (_vip.Category == 2)
            {
                _vipTitle += "(" + VipModule.GetLevel(objMember.Score).Title + ")";
            }
            else if(_vip.Category ==1)
            {
                this.btnUpgradeVip.Visible = true;
            }
        }
        else
        {
            _vipTitle = "普通会员";
        }

        this.txtVip.Text = _vipTitle;

    }

    #region 手动升级VIP
    protected void btnUpgradeVip_Click(object sender, EventArgs e)
    {
        try
        {
            VipEntity _model = new VipEntity();
            _model = VipModule.GetVipByMemberID(this.UserID);
            _model.UpgradeTime = DateTime.Now;
            _model.Category = 2;

            if (VipModule.UpdateVip(_model))
            {
                BindUserBasic();
                this.AddEndScript("Update success", "alert('升级成功！');");
            }
        }
        catch (Exception ex)
        {
            this.AddEndScript("error", "alert('升级失败！');");
        }
    }
    #endregion

    protected void btnModifyDetail_Click(object sender, EventArgs e)
    {
        int wordAddress_Province = Convert.ToInt32(this.ddl_WordAddress_Province.SelectedValue.ToString());
        int wordAddress_City = Convert.ToInt32(this.hd_WordAddress_City.Value.ToString());
        int wordAddress_Area = Convert.ToInt32(this.hd_WordAddress_Area.Value.ToString());

        int homeAddress_Province = Convert.ToInt32(this.ddl_HomeAddress_Province.SelectedValue.ToString());
        int homeAddress_City = Convert.ToInt32(this.hd_HomeAddress_City.Value.ToString());
        int homeAddress_Area = Convert.ToInt32(this.hd_HomeAddress_Area.Value.ToString());
        string duty = this.txt_Duty.Text;
        int cardtype = Int32.Parse(ddl_CardType.SelectedValue);
        string idcard = this.txt_IDCard.Text.Trim();

        string cellphone = this.txt_CellPhone.Text;
        //string homeaddress = txt_HomeAddress.Text.Trim();

        #region 服务器验证

        if (ddl_CardType.SelectedValue.Equals("1"))
        {
            if (idcard.Length != 0)
            {
                if (idcard.Length == 18)
                {
                    //Regex reg = new Regex(@"^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    //if (!reg.IsMatch(idcard))
                    //{
                    //    this.AddEndScript("wrong", "alert('身份证号码输入不正确！')");
                    //    return;
                    //}
                    string chkMsg = PublicFunction.CheckCidInfo(idcard).ToUpper();
                    if (!chkMsg.Contains("CHKPASS"))
                    {
                        this.AddEndScript("wrong", "alert('身份证号码输入不正确！" + chkMsg + "')");
                        return;
                    }
                    Member_Info objMem = new Member_Info();
                    objMem.CustomerID = this.Member.CustomerID;
                    objMem.IDCard = this.txt_IDCard.Text;
                    objMem.Stutas = 0;
                    if (objMem.Exist())
                    {
                        if (this.UserID != objMem.MemberID)
                        {
                            this.AddEndScript("wrong1", "alert('身份证号码已存在！')");
                            return;
                        }
                    }
                }
                else
                {
                    this.AddEndScript("wrong", "alert('身份证号码必须是18位！')");
                    return;
                }
            }
            else
            {
                this.AddEndScript("wrong", "alert('身份证号码不能为空！')");
                return;
            }
        }
        if (this.File1.PostedFile.ContentLength > 204800)
        {
            this.AddEndScript("error", "alert('头像图片过大！');");
            return;
        }

        //2013.3.8验证学习卡
        string cardID = txtCardID.Text;
        if (cardID.Trim().Length != 0)
        {
            MemberCard_Info mci = new MemberCard_Info();
            mci.MemberID=this.UserID;

            mci.CardID = cardID;
            if (!mci.Exist())
            {
                mci=new MemberCard_Info();
                mci.CardID=cardID;
                if (mci.Exist())
                {
                    this.AddEndScript("wrong1", "alert('学习卡号码已存在！')");
                    mci.Dispose();
                    return;
                }
                else
                {
                    mci.Dispose();
                }
            }
            else
            {
                mci.Dispose();
            }
        }
        #endregion

        if (ddl_CardType.SelectedValue == "1")
        {
            ddl_Sex.SelectedValue = CheckIDCardSex(txt_IDCard.Text.Trim()).ToString();
        }

        int status = 0;
        Member_Info objMember = new Member_Info();
        objMember.MemberID = new Guid(Request.QueryString["id"]);
        if (objMember.Exist())
        {
            status = objMember.Stutas;
            objMember.CustomerID = this.Member.CustomerID;

            objMember.RealName = this.txt_RealName.Text;
            if (this.txt_Email.Text.Length > 0)
            {
                objMember.Email = this.txt_Email.Text;
            }
            objMember.Sex = int.Parse(ddl_Sex.SelectedValue) ;

            objMember.Duty = duty;
            objMember.CardType = cardtype;
            objMember.IDCard = idcard;

            objMember.CellPhone = cellphone;
            objMember.WorkAddress_Province = wordAddress_Province;
            objMember.WorkAddress_City = wordAddress_City;
            objMember.WorkAddress_Area = wordAddress_Area;
            objMember.HomeAddress_Province = homeAddress_Province;
            objMember.HomeAddress_City = homeAddress_City;
            objMember.HomeAddress_Area = homeAddress_Area;
            //objMember.HomeAddress = homeaddress;

            if (this.rbt_Y.Checked)
            {
                objMember.Stutas = 0;
            }
            if (this.rbt_N.Checked)
            {
                objMember.Stutas = 1;
            }

            if (this.File1.PostedFile.FileName.Trim().Length != 0)
            {
                string folderName = ResolveClientUrl("~/Data/Header/");
                if (!Directory.Exists(Server.MapPath(folderName)))
                {
                    Directory.CreateDirectory(Server.MapPath(folderName));
                }
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string fileExtension = Path.GetExtension(this.File1.PostedFile.FileName).ToUpper();
                string filePath = Server.MapPath(folderName + fileName + fileExtension);
                if (!(fileExtension == ".JPEG" || fileExtension == ".JPG" || fileExtension == ".PNG" || fileExtension == ".GIF"))
                {
                    this.AddEndScript("error", "alert('不支持的头像图片格式！');");
                    return;
                }
                this.File1.PostedFile.SaveAs(filePath);
                CutImage image = new CutImage();
                image.CutImageSquare(filePath, Server.MapPath(folderName + fileName + "_s" + fileExtension), 71);
                //image.CutImageSquare(filePath, Server.MapPath(folderName + fileName + fileExtension), 71);
                // Delete original upload image
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                // Delete original image
                if (File.Exists(Server.MapPath(folderName + objMember.HeaderUrl)))
                {
                    File.Delete(Server.MapPath(folderName + objMember.HeaderUrl));
                }
                objMember.HeaderUrl = fileName + "_s" + fileExtension;
            }

            //2013.3.8 增加教师，志愿者相关信息
            //objMember.MemberType = int.Parse(ddlMemberType.SelectedValue);
            //objMember.Specialty = txtSpecialty.Text;
            if (chkIsVolunteer.Checked)
            {
                objMember.Volunteer = 1;
            }
            else
            {
                objMember.Volunteer = 0;
            }
            //objMember.Memo = txtMemo.Text;

            if (objMember.Update())
            {
                List<QuestionAttributeDetailEntity> details = ta_Attributes.SelectedValue;
                // 修改该用户的用户标签
                Expo.Training.BRule.Exam.QuestionManager.EditAttributes(objMember.MemberID, details);

                //2013.3.8添加学习卡信息
                MemberCard_Info mci = new MemberCard_Info();
                mci.MemberID = objMember.MemberID;
                if (!mci.Exist())
                {
                    mci.MemberID = objMember.MemberID;
                    mci.CardID = cardID;
                    mci.Add();
                }
                else
                {
                    mci.CardID = cardID;
                    mci.Update();
                }
                mci.Dispose();
                //Modify 2014-10-15
                //增加同步至学分银行的逻辑
                string Score = "0";
                Guid DepartmentID = Guid.Empty;
                string DepartmentName = "";
                //Member_Score ms = new Member_Score();
                //ms.MemberID = objMember.MemberID;
                //if (ms.Exist())
                //{
                //    Score = ms.Score.ToString();
                //}
                Score = Expo.Training.DataAccess.Member.Member.GetUserScore(objMember.MemberID);
                Member_Department MD = new Member_Department();
                Department_Info DI = new Department_Info();
                MD.MemberID = objMember.MemberID;
                if (MD.Exist())
                {
                    DI.DepartmentID = MD.DepartmentID;
                    if (DI.Exist())
                    {
                        DepartmentID = DI.DepartmentID;
                        DepartmentName = DI.DepartmentName;
                    }
                }

                if (MemberAccess.ModifyMemberToBank("", objMember.MemberID.ToString(), objMember.Password, objMember.RealName, "0", objMember.IDCard, "", DepartmentName, DepartmentID.ToString(), Score) == "Fail")
                {
                    AddEndScript("Update success", "alert('同步用户信息失败！请联系管理员!');");
                }
                //ms.Dispose();
                MD.Dispose();
                DI.Dispose();
                //修改用户状态日志
                Audit.AuditLog(this.Member.MemberID, string.Format("{0}|{1}|{2},{3},{4}|{5}", "用户详细信息", "修改", objMember.UserAccount, objMember.RealName, objMember.Stutas == 0 ? "启用" : objMember.Stutas == 1 ? "停用" : objMember.Stutas.ToString(), "成功"));
                AddEndScript("Update success", "alert('修改用户详细资料成功！');");


                WebClient wc = new WebClient();
                //增加是否为管理员的参数
                Member_Group mg = new Member_Group();
                Member_Department md = new Member_Department();
                string DepartmenID = "0";
                md.MemberID = objMember.MemberID;
                mg.MemberID = objMember.MemberID;
                if (mg.Exist())
                {
                    if (md.Exist())
                    {
                        DepartmenID = md.DepartmentID.ToString();
                    }
                }

                string userAccount = objMember.UserAccount;
                string userPwd = objMember.Password;
                //string sendData = "userAccount=" + userAccount + "&userPassword=" + userPwd +
                //                "&sn=2014CiXiXfYh&memberId=" + objMember.MemberID + "&realName=" + objMember.RealName;
                string sendData = "userAccount=" + userAccount + "&userPassword=" + userPwd +
                                "&sn=2014CiXiXfYh&memberId=" + objMember.MemberID + "&realName=" + objMember.RealName +
                                "&userType=" + DepartmenID + "&departmentid=" + DepartmenID;
                byte[] postData = Encoding.GetEncoding("UTF-8").GetBytes(sendData.ToString());
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                wc.Headers.Add("ContentLength", sendData.Length.ToString());
                string Url = ConfigurationManager.AppSettings["Bank"] + "services/UserManager/editUser";
                byte[] recData = wc.UploadData(Url, "Post", postData);
                string JSON = Encoding.GetEncoding("UTF-8").GetString(recData);
                //this.AddEndScript("wrong", "alert('" + al + "');");
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(JSON);
                foreach (KeyValuePair<string, object> str in json)
                {
                    if (str.Key.Equals("result"))
                    {
                        string val = str.Value.ToString();
                        if (val != "0")
                        {
                            AddEndScript("add succes", "alert('学分用户未同步成功！')");
                        }
                    }
                }

                BindUserBasic();
            }
        }
    }

    protected void btnModifyPwd_Click(object sender, EventArgs e)
    {
        string password = this.txt_Password.Text.Trim();
        string password2 = this.txt_Password2.Text.Trim();

        if (password.Length == 0)
        {
            AddEndScript("wrong", "alert('新密码不能为空！');");
            return;
        }
        if (password.Length < 8)
        {
            AddEndScript("wrong", "alert('密码必须至少8位字符！');");
            return;
        }

        if (password2.Length == 0)
        {
            AddEndScript("wrong", "alert('确认密码不能为空！');");
            return;
        }

        if (password != password2)
        {
            this.sp_Password2.Visible = true;
            AddEndScript("wrong", "alert('两次密码输入不一致！');");
            return;
        }

        Member_Info objMember = new Member_Info();
        objMember.MemberID = new Guid(Request.QueryString["id"]);
        if (objMember.Exist())
        {
            if (password.Length != 0 && password != PublicFunction.UnPassword(objMember.Password))
            {
                objMember.Password = PublicFunction.EnPassword(password);
                if (objMember.Update())
                {
                    Expo.Training.BRule.Audit.Audit.AuditLog(this.Member.MemberID, string.Format("{0}|{1}|{2},{3},{4}|{5}", "用户密码信息", "修改", objMember.UserAccount, objMember.RealName, "新密码:" + password, "成功"));
                    AddEndScript("Update success", "alert('修改用户密码成功！');");
                }
            }

            WebClient wc = new WebClient();

            string userAccount = objMember.UserAccount;
            string userPwd = objMember.Password;
            string sendData = "userAccount=" + userAccount + "&userPassword=" + userPwd +
                                "&sn=2014CiXiXfYh&memberId=" + objMember.MemberID + "&realName=" + objMember.RealName;
            byte[] postData = Encoding.GetEncoding("UTF-8").GetBytes(sendData.ToString());
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("ContentLength", sendData.Length.ToString());

            string Url = ConfigurationManager.AppSettings["Bank"]+"services/UserManager/editUser";
            byte[] recData = wc.UploadData(Url, "Post", postData);
            string JSON = Encoding.GetEncoding("UTF-8").GetString(recData);
            //this.AddEndScript("wrong", "alert('" + al + "');");
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(JSON);
            foreach (KeyValuePair<string, object> str in json)
            {
                if (str.Key.Equals("result"))
                {
                    string val = str.Value.ToString();
                    if (val != "0")
                    {
                        AddEndScript("add succes", "alert('学分用户未同步成功！')");
                    }
                }
            }
        }

    }

    private int CheckIDCardSex(string IDCard)
    {
        int idSex = 0;
        try
        {
            idSex = int.Parse(IDCard.Substring(16,1));
            if (idSex % 2 == 0)
            {
                idSex = 2;
            }
            else
            {
                idSex = 1;
            }
        }
        catch (Exception ex)
        {
        }
        return idSex;
    }
}
